package com.shs.riggy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shs.riggy.common.R;
import com.shs.riggy.dto.DishDto;
import com.shs.riggy.entity.Category;
import com.shs.riggy.entity.Dish;
import com.shs.riggy.entity.DishFlavor;
import com.shs.riggy.service.CategoryService;
import com.shs.riggy.service.DishFlavorService;
import com.shs.riggy.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author 晚点再动心
 * @Date 2022/9/13
 */
@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    //菜品口味
    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;
    //菜品信息分页查询
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize,String name){

        Page<Dish> dishPage = new Page<>(page,pageSize);
        Page<DishDto> dtoPage = new Page<>();

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        // 添加过滤条件
        queryWrapper.eq(name != null,Dish::getName,name);

        //  执行分页查询
        dishService.page(dishPage,queryWrapper);

        //  将 dish 中的属性值复制到 dtoPage，但是忽略 records
        //  records需要另外去设置
        BeanUtils.copyProperties(dishPage,dtoPage,"records");

        List<Dish> records = dishPage.getRecords();
        List<DishDto> dtoList = records.stream().map((dish) -> {  // dish 为每个菜品对象
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(dish,dishDto);

            Long categoryId = dish.getCategoryId();  // 菜品的分类id

            Category category = categoryService.getById(categoryId);
            if (category != null){
                dishDto.setCategoryName(category.getName());
            }

            return dishDto;
        }).collect(Collectors.toList());

        dtoPage.setRecords(dtoList);
        return R.success(dtoPage);
        ////构造分页对象
        //Page<Dish> pageInfo = new Page<>(page,pageSize);
        //Page<DishDto> dtoPage = new Page<>();
        //
        ////构造条件查询对象
        //LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //dishLambdaQueryWrapper.like(name != null,Dish::getName,name);
        //dishLambdaQueryWrapper.orderByAsc(Dish::getSort);
        ////执行分页查询
        //dishService.page(pageInfo,dishLambdaQueryWrapper);
        //
        ////经过查询之后，pagininfo中已经有Dish的属性信息，此时我们需要将dish的信息复制到dishdto中
        ////复制信息的过程中排除records字段信息
        //BeanUtils.copyProperties(dtoPage,dishLambdaQueryWrapper,"records");
        //List<Dish> dishList = pageInfo.getRecords();
        //List<DishDto> dtoList = dishList.stream().map((dish) -> {  // dish 为每个菜品对象
        //    DishDto dishDto = new DishDto();
        //
        //    BeanUtils.copyProperties(dish,dishDto);
        //
        //    Long categoryId = dish.getCategoryId();  // 菜品的分类id
        //
        //    //根据id查询分类对象
        //    Category category = categoryService.getById(categoryId);
        //    if (category != null){
        //        dishDto.setCategoryName(category.getName());
        //    }
        //
        //    return dishDto;
        //}).collect(Collectors.toList());
        //
        //dtoPage.setRecords(dtoList);
        //return R.success(dtoPage);
    }

    @PostMapping
    //添加菜品
    public R<String > save(@RequestBody DishDto dishDto){

        log.info("=================添加菜品信息=============");
        //dishService.save(dishDto);
        dishService.saveWithFlavor(dishDto);
        return R.success("添加菜品成功！");
    }
    //根据id获取菜品信息
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        log.info("=================根据id获取菜品信息=============");
        DishDto dishDto = dishService.getByDishIdWithFlavor(id);
        return R.success(dishDto);

    }

    //修改菜品信息
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        log.info("=================修改菜品信息=============");
        dishService.updateWithFlavor(dishDto);
        return R.success("修改菜品信息成功！");
    }

    //根据条件查询对应的菜品信息
    //@GetMapping("/list")
    //public R<List<Dish>> list(Dish dish){
    //
    //    LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
    //    //1代表在售
    //    queryWrapper.eq(Dish::getStatus,1);
    //    queryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
    //    queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
    //    List<Dish> list = dishService.list(queryWrapper);
    //    return R.success(list);
    //}

    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){

        List<DishDto> dishDtoList = null;
        //  根据菜品的分类(湘菜、川菜) 去缓存菜品数据
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();

        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);

        if (dishDtoList != null){
            return R.success(dishDtoList);
        }

        // dishDtoList == null,即Redis中没有 对应的菜品数据，需要去查询数据库
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        Long categoryId = dish.getCategoryId();
        queryWrapper.eq(categoryId != null,Dish::getCategoryId,categoryId);

        // status 为 1: 还在售卖的菜品
        queryWrapper.eq(Dish::getStatus,1);
        // 根据sort 属性升序片排列
        queryWrapper.orderByDesc(Dish::getSort);
        List<Dish> list = dishService.list(queryWrapper);

        dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item, dishDto);

            // 每个item表示 一个菜品 dish，根据菜品的分类id 给菜品设置 菜品的分类名
            Long itemCategoryId = item.getCategoryId();
            Category category = categoryService.getById(itemCategoryId);

            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }

            // 当前菜品的id,根据dishId去查询当前菜品对应的口味
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> flavorQueryWrapper = new LambdaQueryWrapper<>();
            flavorQueryWrapper.eq(DishFlavor::getDishId, dishId);


            List<DishFlavor> dishFlavorList = dishFlavorService.list(flavorQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;

        }).collect(Collectors.toList());

        //  将查询到的菜品数据缓存到Redis,并且设置其 查询到的菜品数据有效时间为1小时，其后会清除菜品该菜品数据
        redisTemplate.opsForValue().set(key,dishDtoList,60L, TimeUnit.MINUTES);
        // 注意: 如果RedisConfig中配置了value的 序列化方式，则存储key-value时，value应该是String类型，而非List类型

        return R.success(dishDtoList);
    }

    @PostMapping("/status/{status}")
    public R<String> updateSaleStatus(@PathVariable("status") Integer status,@RequestParam List<Long> ids){
        //  菜品具体的售卖状态 由前端修改并返回，该方法传入的status是 修改之后的售卖状态，可以直接根据一个或多个菜品id进行查询并修改售卖即可
        log.info("ids :"+ids);
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ids != null,Dish::getId,ids);


        List<Dish> list = dishService.list(queryWrapper);
        if (list != null){
            for (Dish dish : list) {
                dish.setStatus(status);
                dishService.updateById(dish);
            }
            return R.success("菜品的售卖状态已更改！");
        }
        return R.error("售卖状态不可更改,请联系管理员或客服！");

    }

    @DeleteMapping
    public R<String> batchDelete(@RequestParam("ids") List<Long> ids){
        dishService.batchDeleteByIds(ids);

        return R.success("成功删除菜品！");
    }



}
